﻿using GamFi.Admin.API.Application.Contracts.Image.GetImages;
using GamFi.Admin.API.Application.Contracts.Image.UploadImage;
using GamFi.Admin.API.Application.Features.Queries.Image.DeleteImage;
using GamFi.Admin.API.Application.Features.Queries.Image.GetImageById;
using GamFi.Admin.API.Application.Features.Queries.Image.GetImages;
using GamFi.Admin.API.Application.Features.Queries.Image.UploadImage;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace GamFi.Admin.API.WEB.Controllers;

/// <summary>
/// Контроллер для картинок
/// </summary>
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class ImageController(IMediator mediator) : ControllerBase
{
    /// <summary>
    /// Получает список всех картинок.
    /// </summary>
    /// <param name="request"></param>
    /// <param name="cancellationToken">Токен отмены операции.</param>
    /// <returns>Ответ, содержащий картинки.</returns>
    [HttpGet("GetImages")]
    public async Task<GetImagesResponse> GetImages([FromQuery] GetImagesRequest request,
        CancellationToken cancellationToken)
        => await mediator.Send(new GetImagesQuery(request), cancellationToken);

    /// <summary>
    /// Загрузить картинку
    /// </summary>
    /// <param name="image">Картинки</param>
    /// <param name="cancellationToken">Токен отмены</param>
    /// <returns></returns>
    [HttpPost("UploadImage")]
    public async Task<UploadImageResponse> UploadImage(IFormFile image, CancellationToken cancellationToken)
    {
        var request = new UploadImageRequest { Image = image };
        return await mediator.Send(new UploadImageCommand(request), cancellationToken);
    }

    /// <summary>
    /// Получить изображение по ИД
    /// </summary>
    /// <param name="id">Ид изображения</param>
    /// <param name="cancellationToken">Токен отмены</param>
    /// <returns>Бинарные данные</returns>\
    [AllowAnonymous]
    [HttpGet("GetImageById/{id:guid}")]
    public async Task<FileContentResult> GetImageById(Guid id, CancellationToken cancellationToken)
    {
        var result = await mediator.Send(new GetImageByIdQuery(id), cancellationToken);

        return new FileContentResult(fileContents: result.Content, contentType: result.ContentType)
        {
            FileDownloadName = result.FileName
        };
    }

    /// <summary>
    /// Эндпоинт для удаления картинки
    /// </summary>
    /// <param name="id"></param>
    /// <param name="cancellationToken">Токен отмены</param>
    [HttpDelete("DeleteImage/{id:guid}")]
    public async Task DeleteImageAsync(Guid id, CancellationToken cancellationToken)
        => await mediator.Send(new DeleteImageCommand(id), cancellationToken);
}